<template>
    <el-container class="media-manager">
        <!-- 侧边导航 -->
        <el-aside width="200px" class="sidebar">
            <el-menu default-active="all" @select="handleMenuSelect">
                <el-button type="primary" class="upload-btn" @click="showUploadDialog">
                    <el-icon>
                        <Upload />
                    </el-icon>
                    <span>上传文件</span>
                </el-button>
                <el-menu-item index="all">
                    <el-icon>
                        <Folder />
                    </el-icon>
                    <span>全部文件</span>
                </el-menu-item>
                <el-menu-item index="image">
                    <el-icon>
                        <Picture />
                    </el-icon>
                    <span>图片</span>
                </el-menu-item>
                <el-menu-item index="video">
                    <el-icon>
                        <VideoCamera />
                    </el-icon>
                    <span>视频</span>
                </el-menu-item>
                <el-menu-item index="recent">
                    <el-icon>
                        <Clock />
                    </el-icon>
                    <span>最近添加</span>
                </el-menu-item>
            </el-menu>
        </el-aside>

        <!-- 主内容区 -->
        <el-main class="main-content">
            <!-- 搜索和操作栏 -->
            <div class="action-bar">
                <el-input v-model="searchQuery" placeholder="搜索文件..." clearable style="width: 300px"
                    @clear="handleSearchClear">
                    <template #prefix>
                        <el-icon>
                            <Search />
                        </el-icon>
                    </template>
                </el-input>

                <el-button-group>
                    <el-button :type="viewMode === 'grid' ? 'primary' : ''" @click="viewMode = 'grid'">
                        <el-icon>
                            <Grid />
                        </el-icon>
                        网格视图
                    </el-button>
                    <el-button :type="viewMode === 'list' ? 'primary' : ''" @click="viewMode = 'list'">
                        <el-icon>
                            <List />
                        </el-icon>
                        列表视图
                    </el-button>
                </el-button-group>
            </div>

            <!-- 预览区 -->
            <div v-if="selectedMedia" class="preview-area">
                <div v-if="selectedMedia.type === 'image'" class="image-preview">
                    <el-image :src="selectedMedia.url" :preview-src-list="[selectedMedia.url]" fit="contain" />
                </div>
                <div v-else-if="selectedMedia.type === 'video'" class="video-preview">
                    <video controls>
                        <source :src="selectedMedia.url" :type="selectedMedia.mimeType">
                        您的浏览器不支持视频播放
                    </video>
                </div>
            </div>

            <!-- 文件列表 -->
            <div v-if="viewMode === 'grid'" class="media-grid">
                <div v-for="item in filteredMedia" :key="item.id" class="media-item" @click="selectMedia(item)">
                    <div class="thumbnail">
                        <el-image v-if="item.type === 'image'" :src="item.thumbnail" fit="cover" />
                        <div v-else class="video-thumbnail">
                            <el-icon>
                                <VideoPlay />
                            </el-icon>
                            <img :src="item.thumbnail" alt="视频缩略图">
                        </div>
                        <div class="actions">
                            <el-button size="small" circle @click.stop="renameMedia(item)">
                                <el-icon>
                                    <Edit />
                                </el-icon>
                            </el-button>
                            <el-button size="small" circle type="danger" @click.stop="deleteMedia(item)">
                                <el-icon>
                                    <Delete />
                                </el-icon>
                            </el-button>
                        </div>
                    </div>
                    <div class="file-info">
                        <div class="filename">{{ item.name }}</div>
                        <div class="file-meta">
                            <span>{{ formatDate(item.createdAt) }}</span>
                            <span>{{ formatFileSize(item.size) }}</span>
                        </div>
                    </div>
                </div>
            </div>

            <el-table v-else :data="filteredMedia" style="width: 100%">
                <el-table-column prop="name" label="文件名">
                    <template #default="{ row }">
                        <div class="file-cell" @click="selectMedia(row)">
                            <el-icon v-if="row.type === 'image'">
                                <Picture />
                            </el-icon>
                            <el-icon v-else>
                                <VideoCamera />
                            </el-icon>
                            <span>{{ row.name }}</span>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="type" label="类型" width="100" />
                <el-table-column prop="size" label="大小" width="120">
                    <template #default="{ row }">
                        {{ formatFileSize(row.size) }}
                    </template>
                </el-table-column>
                <el-table-column prop="createdAt" label="上传时间" width="180">
                    <template #default="{ row }">
                        {{ formatDate(row.createdAt) }}
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="150">
                    <template #default="{ row }">
                        <el-button size="small" @click="renameMedia(row)">重命名</el-button>
                        <el-button size="small" type="danger" @click="deleteMedia(row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :total="totalItems"
                layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
                @current-change="handlePageChange" />
        </el-main>

        <!-- 上传对话框 -->
        <el-dialog v-model="uploadDialogVisible" title="上传文件" width="50%">
            <el-upload drag multiple :action="uploadUrl" :before-upload="beforeUpload" :on-success="handleUploadSuccess"
                :on-error="handleUploadError">
                <el-icon class="el-icon--upload">
                    <UploadFilled />
                </el-icon>
                <div class="el-upload__text">
                    拖拽文件到此处或<em>点击上传</em>
                </div>
                <template #tip>
                    <div class="el-upload__tip">
                        支持上传图片(jpg/png/gif)和视频(mp4/mov)，单文件不超过50MB
                    </div>
                </template>
            </el-upload>
        </el-dialog>

        <!-- 重命名对话框 -->
        <el-dialog v-model="renameDialogVisible" title="重命名文件" width="30%">
            <el-form :model="renameForm">
                <el-form-item label="新文件名">
                    <el-input v-model="renameForm.newName" autocomplete="off" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="renameDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="confirmRename">确定</el-button>
            </template>
        </el-dialog>
    </el-container>
</template>
  
<script setup>
import { ref, computed, onMounted } from 'vue'
import {
    Upload, Folder, Picture, VideoCamera, Clock,
    Search, Grid, List, Edit, Delete,
    UploadFilled, VideoPlay
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 状态管理
const viewMode = ref('grid') // 'grid' 或 'list'
const selectedMedia = ref(null)
const currentPage = ref(1)
const pageSize = ref(20)
const totalItems = ref(0)
const searchQuery = ref('')
const activeCategory = ref('all')
const uploadDialogVisible = ref(false)
const renameDialogVisible = ref(false)
const renameForm = ref({
    mediaId: null,
    newName: ''
})

// 模拟数据
const mediaList = ref([
    {
        id: 1,
        name: '风景照片.jpg',
        type: 'image',
        url: 'https://example.com/images/1.jpg',
        thumbnail: 'https://example.com/thumbs/1.jpg',
        size: 2456789,
        createdAt: '2023-05-15T10:30:00Z',
        mimeType: 'image/jpeg'
    },
    {
        id: 2,
        name: '产品演示.mp4',
        type: 'video',
        url: 'https://example.com/videos/1.mp4',
        thumbnail: 'https://example.com/thumbs/1-video.jpg',
        size: 15678900,
        createdAt: '2023-05-16T14:45:00Z',
        mimeType: 'video/mp4'
    }
    // 更多数据...
])

// 计算属性
const filteredMedia = computed(() => {
    let result = [...mediaList.value]

    // 按分类筛选
    if (activeCategory.value !== 'all') {
        if (activeCategory.value === 'image') {
            result = result.filter(item => item.type === 'image')
        } else if (activeCategory.value === 'video') {
            result = result.filter(item => item.type === 'video')
        } else if (activeCategory.value === 'recent') {
            const oneWeekAgo = new Date()
            oneWeekAgo.setDate(oneWeekAgo.getDate() - 7)
            result = result.filter(item => new Date(item.createdAt) > oneWeekAgo)
        }
    }

    // 搜索筛选
    if (searchQuery.value) {
        const query = searchQuery.value.toLowerCase()
        result = result.filter(item => item.name.toLowerCase().includes(query))
    }

    // 分页处理
    totalItems.value = result.length
    const start = (currentPage.value - 1) * pageSize.value
    const end = start + pageSize.value
    return result.slice(start, end)
})

// 方法
const showUploadDialog = () => {
    uploadDialogVisible.value = true
}

const beforeUpload = (file) => {
    const isImage = file.type.startsWith('image/')
    const isVideo = file.type.startsWith('video/')
    const isLt50M = file.size / 1024 / 1024 < 50

    if (!isImage && !isVideo) {
        ElMessage.error('只能上传图片或视频文件!')
        return false
    }

    if (!isLt50M) {
        ElMessage.error('文件大小不能超过50MB!')
        return false
    }

    return true
}

const handleUploadSuccess = (response, file) => {
    ElMessage.success(`${file.name} 上传成功`)
    // 这里应该将上传的文件添加到mediaList中
    mediaList.value.unshift({
        id: Date.now(),
        name: file.name,
        type: file.type.startsWith('image/') ? 'image' : 'video',
        url: URL.createObjectURL(file),
        thumbnail: file.type.startsWith('image/')
            ? URL.createObjectURL(file)
            : 'https://example.com/default-video-thumb.jpg',
        size: file.size,
        createdAt: new Date().toISOString(),
        mimeType: file.type
    })
    uploadDialogVisible.value = false
}

const handleUploadError = (error, file) => {
    ElMessage.error(`${file.name} 上传失败: ${error.message}`)
}

const selectMedia = (media) => {
    selectedMedia.value = media
}

const renameMedia = (media) => {
    renameForm.value.mediaId = media.id
    renameForm.value.newName = media.name.split('.')[0] // 去掉扩展名
    renameDialogVisible.value = true
}

const confirmRename = () => {
    const mediaIndex = mediaList.value.findIndex(item => item.id === renameForm.value.mediaId)
    if (mediaIndex !== -1) {
        const media = mediaList.value[mediaIndex]
        const ext = media.name.split('.').pop() // 获取文件扩展名
        mediaList.value[mediaIndex].name = `${renameForm.value.newName}.${ext}`
        ElMessage.success('重命名成功')
        renameDialogVisible.value = false
    }
}

const deleteMedia = (media) => {
    ElMessageBox.confirm(
        `确定要删除 "${media.name}" 吗?`,
        '警告',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    ).then(() => {
        mediaList.value = mediaList.value.filter(item => item.id !== media.id)
        if (selectedMedia.value && selectedMedia.value.id === media.id) {
            selectedMedia.value = null
        }
        ElMessage.success('删除成功')
    }).catch(() => {
        // 用户取消
    })
}

const handleMenuSelect = (index) => {
    activeCategory.value = index
    currentPage.value = 1
}

const handleSearchClear = () => {
    searchQuery.value = ''
    currentPage.value = 1
}

const handleSizeChange = (newSize) => {
    pageSize.value = newSize
    currentPage.value = 1
}

const handlePageChange = (newPage) => {
    currentPage.value = newPage
}

const formatDate = (dateString) => {
    return new Date(dateString).toLocaleString()
}

const formatFileSize = (bytes) => {
    if (bytes === 0) return '0 Bytes'
    const k = 1024
    const sizes = ['Bytes', 'KB', 'MB', 'GB']
    const i = Math.floor(Math.log(bytes) / Math.log(k))
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

onMounted(() => {
    // 这里可以加载初始数据
    totalItems.value = mediaList.value.length
})
</script>
  
<style scoped>
.media-manager {
    height: 100vh;
}

.sidebar {
    background-color: #f5f7fa;
    border-right: 1px solid #e6e6e6;
}

.upload-btn {
    width: 100%;
    margin: 10px 0;
    padding: 12px;
}

.main-content {
    padding: 20px;
}

.action-bar {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
}

.preview-area {
    margin-bottom: 20px;
    border: 1px solid #e6e6e6;
    border-radius: 4px;
    padding: 10px;
    min-height: 300px;
    display: flex;
    justify-content: center;
    align-items: center;
}

.image-preview {
    max-width: 100%;
    max-height: 500px;
}

.video-preview {
    width: 100%;
    max-width: 800px;
}

.video-preview video {
    width: 100%;
}

.media-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
    gap: 20px;
    margin-bottom: 20px;
}

.media-item {
    border: 1px solid #e6e6e6;
    border-radius: 4px;
    overflow: hidden;
    cursor: pointer;
    transition: all 0.3s;
}

.media-item:hover {
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    transform: translateY(-2px);
}

.thumbnail {
    position: relative;
    height: 160px;
    overflow: hidden;
}

.thumbnail .el-image {
    width: 100%;
    height: 100%;
}

.video-thumbnail {
    position: relative;
    width: 100%;
    height: 100%;
}

.video-thumbnail img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.video-thumbnail .el-icon {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    font-size: 40px;
    color: white;
    text-shadow: 0 0 5px rgba(0, 0, 0, 0.5);
}

.actions {
    position: absolute;
    top: 10px;
    right: 10px;
    opacity: 0;
    transition: opacity 0.3s;
}

.media-item:hover .actions {
    opacity: 1;
}

.file-info {
    padding: 10px;
}

.filename {
    font-weight: bold;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.file-meta {
    display: flex;
    justify-content: space-between;
    font-size: 12px;
    color: #909399;
    margin-top: 5px;
}

.file-cell {
    display: flex;
    align-items: center;
    gap: 8px;
    cursor: pointer;
}

.file-cell:hover {
    color: var(--el-color-primary);
}
</style>